package com.shiguiwu.springmybatis.netty.http.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * @description: http处理器
 *
 * 说明
 * 1. SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter
 * 2. HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
 * @author: stone
 * @date: Created by 2022/11/13 20:35
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.netty.http.handler
 */
@Slf4j
public class HttpServerHandler  extends SimpleChannelInboundHandler<HttpObject> {

    //channelRead0 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
        //打印出上下文信息
        log.info("上下文信息，对应的通道 ===> {},对应的管道 ====> {},管道中获取的通道===> {}",
                ctx.channel(),
                ctx.pipeline(),
                ctx.pipeline().channel());

        log.info("当前的处理器 ===> {}", ctx.handler());

        //获取请求信息
        if (httpObject instanceof HttpRequest) {
            log.info("ctx 类型="+ctx.getClass());

            log.info("pipeline hashcode =" + ctx.pipeline().hashCode() + " httpServerHandler hash=" + this.hashCode());

            log.info("httpObject 类型=" + httpObject.getClass());
            log.info("客户端地址 ==> {}" , ctx.channel().remoteAddress());

            HttpRequest request = (HttpRequest) httpObject;

            //封装成url
            URI uri = new URI(request.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                log.info("不做响应处理 ===> {}", uri.getPath());
                return;
            }

            ByteBuf byteBuf = Unpooled.copiedBuffer(("hello, me is a http server,服务器" + ctx.channel().remoteAddress()), CharsetUtil.UTF_8);
            HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

            //设置头部信息
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            response.headers().add(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            //将构建好 response返回
            ctx.writeAndFlush(response);
        }


    }
}
